import classNames from 'classnames';
import React, { useEffect, useRef, useState } from 'react'
import { useSelector } from 'react-redux'
import { Header, ShopList } from 'src/components'
import { CSSTransition } from 'react-transition-group';
import { foodCategory, foodDelivery, foodActivity } from "src/api/getData";
import { getImgPath } from 'src/utils'
import { useQuery } from 'src/utils/hooks'
import './index.scss'

const Food = () => {
    const { latitude, longitude } = useSelector((state) => state);

    const [title, setHeadTitle] = useState('')
    const [foodTitle, setFoodTitle] = useState('')
    const [restaurant_category_id, setRestaurantCategoryId] = useState('')
    const [restaurant_category_ids, setRestaurantCategoryIds] = useState('')
    const [sortBy, setSortBy] = useState('')
    const [category, setCategory] = useState([])
    const [categoryDetail, setCategoryDetail] = useState([])
    const [sortByType, setSortByType] = useState()
    const [Delivery, setDelivery] = useState([])
    const [Activity, setActivity] = useState([])
    const [delivery_mode, setDeliveryMode] = useState()
    const [support_ids, setSupportIds] = useState([])
    const [filterNum, setFilterNum] = useState(0)
    const [confirmStatus, setConfirmStatus] = useState(false)
    const query = useQuery();
    const scrollParentRef = useRef()

    useEffect(() => {

        Promise.all([
            foodCategory(latitude, longitude), //获取category分类左侧数据
            foodDelivery(latitude, longitude), //获取筛选列表的配送方式
            foodActivity(latitude, longitude)//获取筛选列表的商铺活动
        ]).then(([res1, res2, res3]) => {

            //初始化时定位当前category分类左侧默认选择项，在右侧展示出其sub_categories列表
            setCategory(res1.data)
            res1.data.forEach(item => {
                if (query.restaurant_category_id === item.id) {
                    setCategoryDetail(item.sub_categories)
                }
            })
            setDelivery(res2.data)
            setActivity(res3.data)
            //记录support_ids的状态，默认不选中，点击状态取反，status为true时为选中状态
            let arr = []
            res3.data.forEach((item) => {
                arr.push({ status: false, id: item.id })
            });
            setSupportIds(arr)
        })

    }, [latitude, longitude, query.restaurant_category_id])


    useEffect(() => {
        //获取从msite页面传递过来的参数
        setHeadTitle(query.title)
        setFoodTitle(query.title)
        setRestaurantCategoryId(query.restaurant_category_id)
    }, [query])

    // 点击顶部三个选项，展示不同的列表，选中当前选项进行展示，同时收回其他选项
    const chooseType = async (type) => {
        if (sortBy !== type) {
            setSortBy(type)
            //food选项中头部标题发生改变，需要特殊处理
            if (type === "food") {
                setFoodTitle("分类")
            } else {
                //将foodTitle 和 title 进行同步
                setFoodTitle(title)
            }
        } else {
            //再次点击相同选项时收回列表
            setSortBy("")
            if (type === "food") {
                //将foodTitle 和 title 进行同步
                setFoodTitle(title)
            }
        }
    }
    //选中Category左侧列表的某个选项时，右侧渲染相应的sub_categories列表
    const selectCategoryName = (id, index) => {
        //第一个选项 -- 全部商家 因为没有自己的列表，所以点击则默认获取选所有数据
        if (index === 0) {
            setRestaurantCategoryIds(null)
            setSortBy("")
            //不是第一个选项时，右侧展示其子级sub_categories的列表
        } else {
            setRestaurantCategoryId(id)
            setCategoryDetail(category[index].sub_categories)
        }
    }
    //选中Category右侧列表的某个选项时，进行筛选，重新获取数据并渲染
    const getCategoryIds = (id, name) => {
        console.log(id, name)
        setRestaurantCategoryIds(id)
        setSortBy("")
        setFoodTitle(name)
        setHeadTitle(name)
    }
    //点击某个排序方式，获取事件对象的data值，并根据获取的值重新获取数据渲染
    const sortList = (event) => {
        let node;
        // 如果点击的是 span 中的文字，则需要获取到 span 的父标签 p
        if (event.target.nodeName.toUpperCase() !== "P") {
            node = event.target.parentNode;
        } else {
            node = event.target;
        }
        setSortByType(node.getAttribute("data"))
        setSortBy("")
    }
    //筛选选项中的配送方式选择
    const selectDeliveryMode = (id) => {
        //delivery_mode为空时，选中当前项，并且filterNum加一
        if (delivery_mode === null) {
            setFilterNum(filterNum + 1)
            setDeliveryMode(id)
            //delivery_mode为当前已有值时，清空所选项，并且filterNum减一
        } else if (delivery_mode === id) {
            setFilterNum(filterNum - 1)
            setDeliveryMode(null)
            //delivery_mode已有值且不等于当前选择值，则赋值delivery_mode为当前所选id
        } else {
            setDeliveryMode(id)
        }
    }
    //点击商家活动，状态取反
    const selectSupportIds = (index, id) => {
        //数组替换新的值
        support_ids.splice(index, 1, {
            status: !support_ids[index].status,
            id
        });
        //重新计算filterNum的个数
        let filterNumNew = delivery_mode === null ? 0 : 1
        setFilterNum(filterNumNew)
    }
    //只有点击清空按钮才清空数据，否则一直保持原有状态
    const clearSelect = () => {
        let support_ids_new = support_ids.map(item => {
            return {
                ...item,
                status: false
            }
        });
        setSupportIds(support_ids_new)
        setFilterNum(0)
        setDeliveryMode(null)
    }
    //点击确认时，将需要筛选的id值传递给子组件，并且收回列表
    const confirmSelectFun = () => {
        //状态改变时，因为子组件进行了监听，会重新获取数据进行筛选
        setConfirmStatus(!confirmStatus)
        setSortBy("")
    }

    return <div className="page_food" ref={scrollParentRef}>
        <Header title={title} goBack></Header>
        <section className="sort_container">
            {/* <!-- 分类 --> */}
            <div
                className={classNames('sort_item', {
                    'choose_type': sortBy === 'food'
                })}
            >
                <div className="sort_item_container" onClick={() => { chooseType('food') }}>
                    <div className="sort_item_border">
                        <span className={sortBy === 'food' ? "category_title" : ""}
                        >{foodTitle}</span>
                        <svg width="10" height="10" xmlns="http://www.w3.org/2000/svg" version="1.1" className="sort_icon">
                            <polygon points="0,3 10,3 5,8" />
                        </svg>
                    </div>
                </div>

                <CSSTransition
                    classNames="showlist"
                    in={category && sortBy === 'food'}
                    timeout={500}
                    unmountOnExit
                >
                    <section className="category_container sort_detail_type">
                        <section className="category_left">
                            <ul>
                                {
                                    category.map((item, index) => {
                                        return <li key={index}
                                            className={restaurant_category_id === item.id ? "category_left_li category_active" : "category_left_li"}
                                            onClick={() => selectCategoryName(item.id, index)}>
                                            <section>
                                                {index && <img src={getImgPath(item.image_url)} className="category_icon" alt="" />}
                                                <span>{item.name}</span>
                                            </section>
                                            <section>
                                                <span className="category_count">{item.count}</span>
                                                {!!index && <svg width="8" height="8" xmlns="http://www.w3.org/2000/svg" version="1.1" className="category_arrow" >
                                                    <path d="M0 0 L6 4 L0 8" stroke="#bbb" strokeWidth="1" fill="none" />
                                                </svg>}
                                            </section>
                                        </li>
                                    })
                                }
                            </ul>
                        </section>
                        <section className="category_right">
                            <ul>
                                {
                                    categoryDetail.map((item, index) => {
                                        return !!index && <li
                                            key={index}
                                            onClick={() => getCategoryIds(item.id, item.name)}
                                            className={restaurant_category_ids === item.id || (!restaurant_category_ids && index === 0) ? "category_right_li category_right_choosed" : "category_right_li"}
                                        >
                                            <span>{item.name}</span>
                                            <span>{item.count}</span>
                                        </li>
                                    })
                                }
                            </ul>
                        </section>
                    </section>
                </CSSTransition>

            </div>
            {/* <!-- 排序 --> */}
            <div className={sortBy === 'sort' ? "sort_item choose_type" : "sort_item"}>
                <div className="sort_item_container" onClick={() => chooseType('sort')}>
                    <div className="sort_item_border">
                        <span className={sortBy === 'sort' ? "category_title" : ""} >排序</span>
                        <svg width="10" height="10" xmlns="http://www.w3.org/2000/svg" version="1.1" className="sort_icon">
                            <polygon points="0,3 10,3 5,8" />
                        </svg>
                    </div>
                </div>
                <CSSTransition classNames="showlist" in={sortBy === 'sort'} timeout={500} unmountOnExit>
                    <section className="sort_detail_type">
                        <ul className="sort_list_container" onClick={(e) => sortList(e)}>
                            <li className="sort_list_li">
                                <svg>
                                    <use xmlnsXlink="http://www.w3.org/1999/xlink" xlinkHref="#default"></use>
                                </svg>
                                <p data="0"
                                    className={classNames({
                                        sort_select: sortByType === 0
                                    })}
                                >
                                    <span>智能排序</span>
                                    {sortByType === 0 && <svg>
                                        <use xmlnsXlink="http://www.w3.org/1999/xlink" xlinkHref="#selected"></use>
                                    </svg>}
                                </p>
                            </li>
                            <li className="sort_list_li">
                                <svg>
                                    <use xmlnsXlink="http://www.w3.org/1999/xlink" xlinkHref="#distance"></use>
                                </svg>
                                <p data="5"
                                    className={classNames({
                                        sort_select: sortByType === 5
                                    })}
                                >
                                    <span>距离最近</span>
                                    {sortByType === 5 && <svg>
                                        <use xmlnsXlink="http://www.w3.org/1999/xlink" xlinkHref="#selected"></use>
                                    </svg>}
                                </p>
                            </li>
                            <li className="sort_list_li">
                                <svg>
                                    <use xmlnsXlink="http://www.w3.org/1999/xlink" xlinkHref="#hot"></use>
                                </svg>
                                <p data="6"
                                    className={classNames({
                                        sort_select: sortByType === 6
                                    })}
                                >
                                    <span>销量最高</span>
                                    {sortByType === 6 && <svg>
                                        <use xmlnsXlink="http://www.w3.org/1999/xlink" xlinkHref="#selected"></use>
                                    </svg>}
                                </p>
                            </li>
                            <li className="sort_list_li">
                                <svg>
                                    <use xmlnsXlink="http://www.w3.org/1999/xlink" xlinkHref="#price"></use>
                                </svg>
                                <p data="1"
                                    className={classNames({
                                        sort_select: sortByType === 1
                                    })}
                                >
                                    <span>起送价最低</span>
                                    {sortByType === 1 && <svg>
                                        <use xmlnsXlink="http://www.w3.org/1999/xlink" xlinkHref="#selected"></use>
                                    </svg>}
                                </p>
                            </li>
                            <li className="sort_list_li">
                                <svg>
                                    <use xmlnsXlink="http://www.w3.org/1999/xlink" xlinkHref="#speed"></use>
                                </svg>
                                <p data="2"
                                    className={classNames({
                                        sort_select: sortByType === 2
                                    })}
                                >
                                    <span>配送速度最快</span>
                                    {sortByType === 2 && <svg>
                                        <use xmlnsXlink="http://www.w3.org/1999/xlink" xlinkHref="#selected"></use>
                                    </svg>}
                                </p>
                            </li>
                            <li className="sort_list_li">
                                <svg>
                                    <use xmlnsXlink="http://www.w3.org/1999/xlink" xlinkHref="#rating"></use>
                                </svg>
                                <p data="3"
                                    className={classNames({
                                        sort_select: sortByType === 3
                                    })}
                                >
                                    <span>评分最高</span>
                                    {sortByType === 3 && <svg>
                                        <use xmlnsXlink="http://www.w3.org/1999/xlink" xlinkHref="#selected"></use>
                                    </svg>}
                                </p>
                            </li>
                        </ul>
                    </section>
                </CSSTransition>
            </div>
            {/* <!-- 筛选 --> */}
            <div className={sortBy === 'activity' ? "sort_item choose_type" : "sort_item"} >
                <div className="sort_item_container" onClick={() => chooseType('activity')}>
                    <span className={sortBy === 'activity' ? "category_title" : ""} >筛选</span>
                    <svg width="10" height="10" xmlns="http://www.w3.org/2000/svg" version="1.1" className="sort_icon">
                        <polygon points="0,3 10,3 5,8" />
                    </svg>
                </div>
                <CSSTransition classNames="showlist" in={sortBy === 'activity'} timeout={500} unmountOnExit>
                    <section className="sort_detail_type filter_container">
                        <section style={{ width: '100%' }}>
                            <header className="filter_header_style">配送方式</header>
                            <ul className="filter_ul">
                                {
                                    Delivery.map((item, index) => {
                                        return <li key={index} className="filter_li" onClick={() => selectDeliveryMode(item.id)}>
                                            <svg style={{ opacity: (item.id === 0) && (delivery_mode !== 0) ? 0 : 1 }}

                                            >
                                                <use xmlnsXlink="http://www.w3.org/1999/xlink" xlinkHref={delivery_mode === item.id ? '#selected' : '#fengniao'}></use>
                                            </svg>
                                            <span className={classNames({ selected_filter: delivery_mode === item.id })}>{item.text}</span>
                                        </li>
                                    })
                                }
                            </ul>
                        </section>
                        <section style={{ width: '100%' }}>
                            <header className="filter_header_style">商家属性（可以多选）</header>
                            <ul className="filter_ul" style={{ paddingBottom: '.5rem' }}>
                                {
                                    Activity.map((item, index) => {
                                        let support_item = support_ids[index] || {}
                                        return <li key={index} className="filter_li" onClick={() => selectSupportIds(index, item.id)}>
                                            {support_item.status && <svg className="activity_svg">
                                                <use xmlnsXlink="http://www.w3.org/1999/xlink" xlinkHref="#selected"></use>
                                            </svg>}
                                            {!support_item.status && <span className="filter_icon" style={{
                                                color: '#' + item.icon_color,
                                                borderColor: '#' + item.icon_color
                                            }}>{item.icon_name}</span>}
                                            <span className={classNames({ selected_filter: support_item.status })}>{item.name}</span>
                                        </li>
                                    })
                                }
                            </ul>
                        </section>
                        <footer className="confirm_filter">
                            <div className="clear_all filter_button_style" onClick={clearSelect}>清空</div>
                            <div className="confirm_select filter_button_style" onClick={confirmSelectFun}>确定{filterNum && <span>({filterNum})</span>}</div>
                        </footer>
                    </section>

                </CSSTransition>
            </div>
        </section>
        <CSSTransition classNames="showcover" in={!!sortBy} timeout={500} unmountOnExit>
            <div className="back_cover" />
        </CSSTransition>
        <section className="shop_list_container">
            {latitude && <ShopList
                restaurantCategoryId={restaurant_category_id}
                restaurantCategoryIds={restaurant_category_ids}
                sortByType={sortByType}
                deliveryMode={delivery_mode}
                confirmSelect={confirmStatus}
                supportIds={support_ids}
                scrollParentRef={scrollParentRef}
            >
            </ShopList>}
        </section>
    </div>
}

export default Food